package org.airlink.persistence.criteria
{
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	
	import flex.persistence.EntityManager;
	import flex.persistence.criteria.Path;
	import flex.persistence.metamodel.Attribute;
	import flex.persistence.metamodel.Type;
	
	import org.airlink.persistence.Entity;
	import org.airlink.persistence.EntityIntrospector;
	import org.airlink.persistence.EntityManagerImpl;
	import org.airlink.persistence.metamodel.AttributeImpl;
	
	public class PathImpl extends ExpressionImpl implements Path 
	{
		
		protected var _parent:PathImpl;
		protected var _attribute:Attribute;	
		
		//index de l'alias de la table ; 
		//ex : SELECT * FROM RandomTable t1 ;
		//              aliasIndex = 1    ^		
		protected var _aliasIndex:uint;		
		
		public function PathImpl(cls:Class = null, parent:PathImpl = null, attribute:Attribute = null, em:EntityManagerImpl = null, aliasIndex:uint = 0)	{		
			super(cls,em);
			_aliasIndex = aliasIndex;
			_attribute = attribute;
			_parent = parent;					
		}	
		
		//transformer en get(cls:Class, champs:String) ?
		public function get(attributeName:String):Path{				
			return new PathImpl(_cls, this, new AttributeImpl(_cls,attributeName,_em,_aliasIndex),_em);
		}	
		
		public static function getClass(asType:String):Class {					
			return getDefinitionByName(asType) as Class;
		}
		
		override public function toString():String{
			var result:String="";		
			if(_attribute!=null)
				result+=_attribute.asValue();	
			else {
				
				var entity:Entity = _em.introspector.loadMetadata(_cls);
				if(entity.tableName != null)
					result += entity.tableName;
				else
				result+=getClassName(_cls);
			}
			
			
			return result ;
		}		
		
		
		private function getClassName(object:Object):String {
			if(object!=null)
				return getQualifiedClassName(object).split("::").pop();			
			return null;
		}		
		

		public function get aliasIndex():uint{
			return _aliasIndex;
		}
		public function set aliasIndex(aliasIndex:uint):void{
			_aliasIndex=aliasIndex;
		}
		
	}
}